#include "food.h"
#include <ctime>
#include <cstdlib>
#include <algorithm> // 添加头文件

Food::Food(int screenWidth, int screenHeight, int gridSize)
    : screenWidth(screenWidth), screenHeight(screenHeight), gridSize(gridSize) {
    std::srand(static_cast<unsigned int>(std::time(nullptr)));
    respawn();
}

void Food::respawn() {
    // 确保在有效区域内生成
    int cols = (screenWidth - gridSize) / gridSize;
    int rows = (screenHeight - gridSize) / gridSize;

    int x, y;
    bool validPosition = false;

    // 尝试10次找到有效位置
    for (int i = 0; i < 10; i++) {
        x = (std::rand() % cols) * gridSize;
        y = (std::rand() % rows) * gridSize;

        // 检查是否在蛇身上（实际项目中需要蛇身位置）
        // 这里简化处理，只确保在屏幕内
        if (x >= 0 && x < screenWidth - gridSize &&
            y >= 0 && y < screenHeight - gridSize) {
            validPosition = true;
            break;
        }
    }

    // 如果没找到有效位置，使用默认位置
    if (!validPosition) {
        x = screenWidth / 2;
        y = screenHeight / 2;
    }

    collisionBox = RectangleCollisionBox(x, y, gridSize, gridSize);
}

const RectangleCollisionBox& Food::getCollisionBox() const {
    return collisionBox;
}